<?
class desincorporacion{

	// Propiedades
	var $id;
	var $letra_per;
	var $cedula_per; 
	var $nombre_per; 
	var $direccion_per; 
	var $telefono_per;
	var $id_zona; 
	var $id_perito;
	var $fecha;
	var $numero;	
	var $hora; 
	var $lugar_inspeccion; 
	var $condicion_final; 
	var $carroceria_veh; 
	var $placa_veh; 
	var $marca_veh; 
	var $modelo_veh; 
	var $tipo_veh; 
	var $anio_veh; 
	var $color_veh; 
	var $uso_veh; 
	var $chasis_veh; 
	var $motor_veh; 
	var $carrozado_veh; 
	var $clase_veh; 
	var $puestos_veh; 
	var $ejes_veh; 
	var $tara_veh; 
	var $capacidad_carga_veh; 
	var $servicio_veh; 
	var $registro_veh; 
	var $zona_c; 
	var $zona_d; 
	var $zona_t; 
	var $danos; 
	var $condiciones; 
	var $foto1; 
	var $foto2; 
	var $foto3; 
	var $foto4; 
	var $foto5; 
	var $pagos;
	var $monto_pagos;
	var $valor_final;
	var $observaciones;

	var $total;
	
	function get($conn, $id){
		try {
			$q = "SELECT 
					A.*, lpad(A.numero::text, 10, '0') AS numero2, 
					C.letra AS letra_per, C.cedula AS cedula_per, C.nombre AS nombre_per,
					C.direccion AS direccion_per, C.telefono AS telefono_per,
					CASE WHEN strpos(B.placa,'S/P')=1 THEN NULL ELSE B.placa END  AS placa_veh, 
					B.carroceria AS carroceria_veh, 
					B.id_marca AS marca_veh, B.id_modelo AS modelo_veh, B.id_color AS color_veh, 
					B.anio AS anio_veh, B.id_tipo AS tipo_veh,
					B.id_tipo AS tipo_veh, B.anio AS anio_veh, B.id_uso AS uso_veh, B.carroceria AS carroceria_veh,
					B.motor AS motor_veh, B.id_color AS color_veh, B.serial_carrozado AS carrozado_veh, B.clase AS clase_veh,
					B.puestos AS puestos_veh, B.ejes AS  ejes_veh, B.tara AS tara_veh, B.capacidad_carga AS capacidad_carga_veh,
					B.servicio AS servicio_veh, B.registro AS registro_veh, B.chasis AS chasis_veh,
					(SELECT ubicacion FROM fotos_desincorporacion WHERE id_desincorporacion = A.id AND ubicacion ILIKE 'images/desinc/' || A.id || '-1%' LIMIT 1) AS foto1, 
					(SELECT ubicacion FROM fotos_desincorporacion WHERE id_desincorporacion = A.id AND ubicacion ILIKE 'images/desinc/' || A.id || '-2%' LIMIT 1) AS foto2, 
					(SELECT ubicacion FROM fotos_desincorporacion WHERE id_desincorporacion = A.id AND ubicacion ILIKE 'images/desinc/' || A.id || '-3%' LIMIT 1) AS foto3, 
					(SELECT ubicacion FROM fotos_desincorporacion WHERE id_desincorporacion = A.id AND ubicacion ILIKE 'images/desinc/' || A.id || '-4%' LIMIT 1) AS foto4, 
					(SELECT ubicacion FROM fotos_desincorporacion WHERE id_desincorporacion = A.id AND ubicacion ILIKE 'images/desinc/' || A.id || '-5%' LIMIT 1) AS foto5
				FROM desincorporaciones AS A 
					LEFT JOIN vehiculos AS B ON A.id_vehiculo = B.id
					LEFT JOIN personas AS C ON A.id_persona = C.id
				WHERE A.id=$id";
			//die($q);
			$r = $conn->Execute(utf8_encode($q));
			if(!$r->EOF){

				$this->id = $r->fields['id'];
				$this->letra_per = $r->fields['letra_per'];
				$this->cedula_per = $r->fields['cedula_per'];
				$this->nombre_per = $r->fields['nombre_per'];
				$this->direccion_per = $r->fields['direccion_per'];
				$this->telefono_per = $r->fields['telefono_per'];
				$this->id_zona = $r->fields['id_zona'];
				$this->id_perito = $r->fields['id_perito'];
				$this->fecha = $r->fields['fecha'];
				$this->hora = $r->fields['hora'];
				$this->numero = $r->fields['numero2'];				
				$this->lugar_inspeccion = $r->fields['lugar_inspeccion'];
				$this->condicion_final = $r->fields['condicion_final'];
				$this->carroceria_veh = $r->fields['carroceria_veh'];
				$this->placa_veh = $r->fields['placa_veh'];
				$this->marca_veh = $r->fields['marca_veh'];
				$this->modelo_veh = $r->fields['modelo_veh'];
				$this->tipo_veh = $r->fields['tipo_veh'];
				$this->anio_veh = $r->fields['anio_veh'];
				$this->color_veh = $r->fields['color_veh'];
				$this->uso_veh = $r->fields['uso_veh'];
				$this->chasis_veh = $r->fields['chasis_veh'];
				$this->motor_veh = $r->fields['motor_veh'];
				$this->carrozado_veh = $r->fields['carrozado_veh'];
				$this->clase_veh = $r->fields['clase_veh'];
				$this->puestos_veh = $r->fields['puestos_veh'];
				$this->ejes_veh = $r->fields['ejes_veh'];
				$this->tara_veh = $r->fields['tara_veh'];
				$this->capacidad_carga_veh = $r->fields['capacidad_carga_veh'];
				$this->servicio_veh = $r->fields['servicio_veh'];
				$this->registro_veh = $r->fields['registro_veh'];
				$this->ubicacion_danos = $r->fields['ubicacion_danos'];
				$this->foto1 = $r->fields['foto1'];
				$this->foto2 = $r->fields['foto2'];
				$this->foto3 = $r->fields['foto3'];
				$this->foto4 = $r->fields['foto4'];
				$this->foto5 = $r->fields['foto5'];
				$this->observaciones = $r->fields['observaciones'];
				
				$q = "SELECT A.*,B.nombre AS banco FROM formas_pago_desincorporacion AS A LEFT JOIN bancos AS B ON A.id_banco = B.id WHERE id_desincorporacion=$id";
				$rCF = $conn->Execute(utf8_encode($q));
				$i=0;
				$this->monto_pagos=0;

				while(!$rCF->EOF){
					$PagosAux[$i][0] = $rCF->fields['tipo_pago'];
					$PagosAux[$i][1] = $rCF->fields['id_banco'];
					$PagosAux[$i][2] = $rCF->fields['banco'];
					$PagosAux[$i][3] = $rCF->fields['referencia'];
					$PagosAux[$i][4] = $rCF->fields['monto'];

					$this->monto_pagos+= $rCF->fields['monto'];

					$i++;
					$rCF->movenext();
				}
				$this->pagos = new Services_JSON();
				$this->pagos = is_array($PagosAux) ? $this->pagos->encode($PagosAux) : false;
					
				$q = "SELECT B.id, B.nombre, CASE WHEN A.id IS NOT NULL THEN 1 ELSE 0 END AS Valor
					FROM danos_desincorporacion AS A
						RIGHT JOIN tipos_danos_desincorporaciones AS B ON A.id_tipo_dano = B.id AND A.id_desincorporacion = $this->id
					ORDER BY B.orden";
				//die($q);
				$rCF = $conn->Execute(utf8_encode($q));
				$i=0;

				while(!$rCF->EOF){
					$DanosAux[$i][0] = $rCF->fields['id'];
					$DanosAux[$i][1] = $rCF->fields['nombre'];
					$DanosAux[$i][2] = $rCF->fields['valor'];
					$i++;
					$rCF->movenext();
				}

				$this->danos = new Services_JSON();
				$this->danos = is_array($DanosAux) ? $this->danos->encode($DanosAux) : false;
					
				$q = "SELECT B.inicia_grupo, B.id AS id_componente, B.nombre, COALESCE(C.id,-1) AS id_condicion, A.maximo * A.porcentaje / 100 AS valor  FROM evaluacion_desincorporacion AS A
						RIGHT JOIN componentes_evaluacion  AS B ON A.id_componente=B.id AND A.id_desincorporacion = $this->id
						LEFT JOIN condiciones_funcionales AS C ON A.id_condicion=C.id 
					ORDER BY B.codigo";
				//die($q);
				$rCF = $conn->Execute(utf8_encode($q));
				$i=0;
				
				$tmp_valor_final = 0;

				while(!$rCF->EOF){
					$CondicionesAux[$i][0] = $rCF->fields['id_componente'];
					$CondicionesAux[$i][1] = $rCF->fields['nombre'];
					$CondicionesAux[$i][2] = $rCF->fields['id_condicion'];
					$CondicionesAux[$i][3] = $rCF->fields['inicia_grupo'];
					$CondicionesAux[$i][4] = $rCF->fields['valor'];
					
					$tmp_valor_final += $rCF->fields['valor'];
					
					$i++;
					$rCF->movenext();
				}

				$this->condiciones = new Services_JSON();
				$this->condiciones = is_array($CondicionesAux) ? $this->condiciones->encode($CondicionesAux) : false;
				
				$this->valor_final = $tmp_valor_final;
			}
			 
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}
	
	function get_all($conn, $orden="A.id DESC", $Tipo, $Valor, $TipoE, $max=10, $from=1){
		try {
			$zona = $_SESSION['SesionZona'];
			$TipoE = empty($TipoE) ? 0 : $TipoE;
			if(empty($Valor)){
			$q = "SELECT A.id FROM desincorporaciones AS A WHERE A.id_zona = $zona";
			$q.= "ORDER BY $orden ";
			}
			elseif($Tipo==0){
			$q = "SELECT A.id FROM desincorporaciones AS A ";
			$q.= "WHERE A.id_zona = $zona AND A.id::text ILIKE '%$Valor%'::text ";
			$q.= "ORDER BY $orden ";
			}
			elseif($Tipo==1){
			$q = "SELECT A.id FROM desincorporaciones AS A ";
			$q.= "WHERE A.id_zona = $zona AND A.numero::text ILIKE '%$Valor%'::text ";
			$q.= "ORDER BY $orden ";
			}
			elseif($Tipo==2){
			$q = "SELECT A.id FROM desincorporaciones AS A ";
			$q.= "INNER JOIN personas AS B ON A.id_persona = B.id ";
			$q.= "WHERE A.id_zona = $zona AND B.cedula::text ILIKE '%$Valor%'::text ";
			$q.= "ORDER BY $orden ";
			}
			elseif($Tipo==3){
			$q = "SELECT A.id FROM desincorporaciones AS A ";
			$q.= "INNER JOIN personas AS B ON A.id_persona = B.id ";
			$q.= "WHERE A.id_zona = $zona AND  B.nombre::text ILIKE '%$Valor%'::text ";
			$q.= "ORDER BY $orden ";
			}
			elseif($Tipo==4){
			$q = "SELECT A.id FROM desincorporaciones AS A ";
			$q.= "INNER JOIN vehiculos AS C ON A.id_vehiculo = C.id ";
			$q.= "WHERE A.id_zona = $zona AND  C.placa::text ILIKE '%$Valor%'::text  ";
			$q.= "ORDER BY $orden ";
			}
			//die($q);
			
			$r = ($max!=0) ? $conn->SelectLimit($q, $max, $from) : $conn->Execute(utf8_encode($q));
			$coleccion=array();
			
			while(!$r->EOF){
				$ue = new desincorporacion;
				$ue->get($conn, $r->fields['id']);
				$coleccion[] = $ue;
				$r->movenext();
			}
			$this->total = $r->RecordCount();
			return $coleccion;
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}
	
	function __destruct(){
    }
	
	function add($conn, $letra_per, $cedula_per, $nombre_per, $direccion_per, $telefono_per, $id_zona, $id_perito, $fecha,	$hora, $lugar_inspeccion, $condicion_final, $carroceria_veh, $placa_veh, $marca_veh, $modelo_veh, $tipo_veh, $anio_veh, $color_veh, $uso_veh, $chasis_veh, $motor_veh, $carrozado_veh, $clase_veh, $puestos_veh, $ejes_veh, $tara_veh, $capacidad_carga_veh, $servicio_veh, $registro_veh, $zona_c, $zona_d, $zona_t, $danos, $condiciones, $foto1, $foto2, $foto3, $foto4, $foto5, $pagos, $observaciones){
		try {
 
			$ubicacion_danos = $zona_c . $zona_d . $zona_t;
			
			//Verificar Existencia Persona
			$opersona = new persona;

			$q = "SELECT * FROM personas WHERE letra= '$letra_per' AND cedula = '$cedula_per'";
			$r = $conn->Execute(utf8_encode($q));
			if (!$r->EOF) {
				$opersona->set($conn, $r->fields['id'], $cedula_per, $nombre_per, $direccion_per, $telefono_per, $letra_per);
				$id_per = $r->fields['id'];
			} else {
				$opersona->add($conn, $cedula_per, $nombre_per, $direccion_per, $telefono_per, $letra_per);
				$q = "SELECT * FROM personas WHERE letra='$letra_per' AND cedula = '$cedula_per'";
				$r = $conn->Execute(utf8_encode($q));
				if (!$r->EOF) {
					$id_per = $r->fields['id'];
				}

			}
			

			//Verificar Existencia de Vehiculo
			$ovehiculo = new vehiculo;

			$q = "SELECT * FROM vehiculos WHERE carroceria = upper('$carroceria_veh')";
			$r = $conn->Execute(utf8_encode($q));
			
			if (!$r->EOF) {
				$ovehiculo->set($conn, $r->fields['id'], $placa_veh, $marca_veh, $modelo_veh, -1, $color_veh, $anio_veh, -1, $carroceria_veh, '');
				$id_veh = $r->fields['id'];
			} else {
				//$r = $ovehiculo->add_returning($conn, $placa_veh, $marca_veh, $modelo_veh, -1, $color_veh, $anio_veh, -1, $carroceria_veh, '');
				$r = $ovehiculo->add_returning2($conn, $placa_veh, $marca_veh, $modelo_veh, $tipo_veh, $color_veh, $anio_veh, $uso_veh, $carroceria_veh, $motor_veh, $carrozado_veh, $clase_veh, $puestos_veh, $ejes_veh, $tara_veh, $capacidad_carga_veh, $servicio_veh, $registro_veh);
				
				//$q = "SELECT MAX(id) AS id FROM vehiculos WHERE carroceria = '$carroceria_veh'";
				//$r = $conn->Execute(utf8_encode($q));
				//if (!$r->EOF) {
				//	$id_veh = $r->fields['id'];
				//}
				$id_veh = $r;
			
			}

			
			$q = "INSERT INTO desincorporaciones ";
			$q.= "( id_zona, id_perito, id_vehiculo, id_persona, fecha, hora, lugar_inspeccion,condicion_final, ubicacion_danos, observaciones) ";
			$q.= "VALUES ";
			$q.= "( $id_zona, NULLIF($id_perito,-1), $id_veh, $id_per, '$fecha', '$hora', upper('$lugar_inspeccion') , upper('$condicion_final'), upper('$ubicacion_danos'), upper('$observaciones')); ";
			//$q.= "RETURNING id";
			
			//die($q);

			$r = $conn->Execute(utf8_encode($q));

			$this->auditoria($conn, $q);
			
			$q2 = "SELECT MAX(id) AS id FROM desincorporaciones";
			$r2 = $conn->Execute(utf8_encode($q2));
			
			//$this->GuardarPagos($conn, $r->fields['id'],$pagos);
			//$this->GuardarPagos($conn, $r2->fields['id'],$pagos);
			$this->GuardarDanos($conn, $r2->fields['id'],$danos);
			$this->GuardarCondiciones($conn, $r2->fields['id'],$condiciones);
			
			return REG_ADD_OK;
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}

	function set($conn, $id, $letra_per, $cedula_per, $nombre_per, $direccion_per, $telefono_per, $id_zona, $id_perito, $fecha,	$hora, $lugar_inspeccion, $condicion_final, $carroceria_veh, $placa_veh, $marca_veh, $modelo_veh, $tipo_veh, $anio_veh, $color_veh, $uso_veh, $chasis_veh, $motor_veh, $carrozado_veh, $clase_veh, $puestos_veh, $ejes_veh, $tara_veh, $capacidad_carga_veh, $servicio_veh, $registro_veh, $zona_c, $zona_d, $zona_t, $danos, $condiciones, $foto1, $foto2, $foto3, $foto4, $foto5, $pagos, $elimina_foto1, $elimina_foto2, $elimina_foto3, $elimina_foto4, $elimina_foto5, $observaciones){
		try {
			$ubicacion_danos = $zona_c . $zona_d . $zona_t;
			
			//Verificar Existencia Persona
			$opersona = new persona;

			$q = "SELECT * FROM personas WHERE letra= '$letra_per' AND cedula = '$cedula_per'";
			$r = $conn->Execute(utf8_encode($q));
			if (!$r->EOF) {
				$opersona->set($conn, $r->fields['id'], $cedula_per, $nombre_per, $direccion_per, $telefono_per, $letra_per);
				$id_per = $r->fields['id'];
			} else {
				$opersona->add($conn, $cedula_per, $nombre_per, $direccion_per, $telefono_per, $letra_per);
				$q = "SELECT * FROM personas WHERE letra='$letra_per' AND cedula = '$cedula_per'";
				$r = $conn->Execute(utf8_encode($q));
				if (!$r->EOF) {
					$id_per = $r->fields['id'];
				}

			}
			

			//Verificar Existencia de Vehiculo
			$ovehiculo = new vehiculo;

			$q = "SELECT * FROM vehiculos WHERE carroceria = upper('$carroceria_veh')";
			$r = $conn->Execute(utf8_encode($q));
			
			if (!$r->EOF) {
				$ovehiculo->set($conn, $r->fields['id'], $placa_veh, $marca_veh, $modelo_veh, -1, $color_veh, $anio_veh, -1, $carroceria_veh, '');
				$id_veh = $r->fields['id'];
			} else {
				//$r = $ovehiculo->add_returning($conn, $placa_veh, $marca_veh, $modelo_veh, -1, $color_veh, $anio_veh, -1, $carroceria_veh, '');
				$r = $ovehiculo->add_returning2($conn, $placa_veh, $marca_veh, $modelo_veh, $tipo_veh, $color_veh, $anio_veh, $uso_veh, $carroceria_veh, $motor_veh, $carrozado_veh, $clase_veh, $puestos_veh, $ejes_veh, $tara_veh, $capacidad_carga_veh, $servicio_veh, $registro_veh);
				
				//$q = "SELECT MAX(id) AS id FROM vehiculos WHERE carroceria = '$carroceria_veh'";
				//$r = $conn->Execute(utf8_encode($q));
				//if (!$r->EOF) {
				//	$id_veh = $r->fields['id'];
				//}
				$id_veh = $r;
			
			}

			$q = "UPDATE desincorporaciones ";
			$q.= "SET id_zona = $id_zona, id_perito = NULLIF($id_perito,-1), id_vehiculo = $id_veh, id_persona = $id_per, fecha = '$fecha', hora = '$hora', lugar_inspeccion = upper('$lugar_inspeccion'), condicion_final = upper('$condicion_final'), ubicacion_danos = upper('$ubicacion_danos'), observaciones = upper('$observaciones') ";
			$q.= "WHERE id = $id";
			//die($q);
	
			$r = $conn->Execute(utf8_encode($q));
			
			$this->auditoria($conn, $q);

			//$this->GuardarPagos($conn, $id, $pagos);
			$this->GuardarDanos($conn, $id, $danos);
			$this->GuardarCondiciones($conn, $id, $condiciones);

			if($elimina_foto1=="on") {
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-1%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-1%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				
			}
			
			if(!empty($foto1)){

				//$q="DELETE FROM fotos_experticia WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-1%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-1%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}

				$q="INSERT INTO fotos_desincorporacion(id_desincorporacion, ubicacion) VALUES ($id,'$foto1');";
				$conn->Execute($q);
				
				$this->auditoria($conn, $q);
			}

			if($elimina_foto2=="on") {
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-2%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-2%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				
				
			}

			if(!empty($foto2)){
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-2%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-2%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}
				
				$q="INSERT INTO fotos_desincorporacion(id_desincorporacion, ubicacion) VALUES ($id,'$foto2');";
				$conn->Execute($q);
				$this->auditoria($conn, $q);
			}

			if($elimina_foto3=="on") {
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-3%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-3%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				
				
			}

			if(!empty($foto3)){
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-3%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-3%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				

				$q="INSERT INTO fotos_desincorporacion(id_desincorporacion, ubicacion) VALUES ($id,'$foto3');";
				$conn->Execute($q);
				
				$this->auditoria($conn, $q);
			}

			if($elimina_foto4=="on") {
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-4%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-4%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				
				
			}

			if(!empty($foto4)){
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-4%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-4%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				

				$q="INSERT INTO fotos_desincorporacion(id_desincorporacion, ubicacion) VALUES ($id,'$foto4');";
				$conn->Execute($q);
				
				$this->auditoria($conn, $q);
			}			

			if($elimina_foto5=="on") {
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-5%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-5%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				
				
			}

			if(!empty($foto5)){
				//$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-5%' RETURNING ubicacion;";
				$q="DELETE FROM fotos_desincorporacion WHERE id_desincorporacion = $id AND ubicacion ILIKE 'images/desinc/$id-5%';";
				$r = $conn->Execute($q);
				
				if (!$r->EOF){
					$this->auditoria($conn, $q);
					unlink($r->fields['ubicacion']);
				}				

				$q="INSERT INTO fotos_desincorporacion(id_desincorporacion, ubicacion) VALUES ($id,'$foto5');";
				$conn->Execute($q);
				
				$this->auditoria($conn, $q);
			}			
						
			
			return REG_SET_OK;

		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}

	function del($conn, $id){
		try {
			$q = "DELETE FROM desincorporaciones WHERE id=$id";
			//die($q);
			$conn->Execute(utf8_encode($q));
			
			$this->auditoria($conn, $q);
			
			return REG_DEL_OK;
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}

	function GuardarPagos($conn,$id,$pagos){
		try {
			$JsonRec = new Services_JSON();
			$JsonRec=$JsonRec->decode(str_replace("\\","",$pagos));
			$q = "DELETE FROM formas_pago_desincorporacion WHERE id_desincorporacion=$id";
			$r = $conn->Execute(utf8_encode($q));
			
			$this->auditoria($conn, $q);
			
			if(is_array($JsonRec->pagos)){
				foreach($JsonRec->pagos as $pagosAux){
					$monto = guardafloat($pagosAux[4]);
					$q = "INSERT INTO formas_pago_desincorporacion ";
					$q.= "(id_desincorporacion, tipo_pago, id_banco,  referencia, monto) ";
					$q.= "VALUES ";
					$q.= "($id, $pagosAux[0], NULLIF('$pagosAux[1]','')::integer, upper('$pagosAux[3]'), $monto); ";
					
					//die($q);
					$conn->Execute(utf8_encode($q));
					
					$this->auditoria($conn, $q);
				}
			}
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}

	function GuardarDanos($conn,$id,$danos){
		try {
			$JsonRec = new Services_JSON();
			$JsonRec=$JsonRec->decode(str_replace("\\","",$danos));
			$q = "DELETE FROM danos_desincorporacion WHERE id_desincorporacion=$id";
			$r = $conn->Execute(utf8_encode($q));
			
			$this->auditoria($conn, $q);
			
			if(is_array($JsonRec->danos)){
				foreach($JsonRec->danos as $danosAux){
					if ($danosAux[1]!="0"){
						$monto = guardafloat($pagosAux[4]);
						$q = "INSERT INTO danos_desincorporacion ";
						$q.= "(id_desincorporacion, id_tipo_dano) ";
						$q.= "VALUES ";
						$q.= "($id, $danosAux[0]); ";
						
						//die($q);
						$conn->Execute(utf8_encode($q));
						
						$this->auditoria($conn, $q);
					}
				}
			}
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}

	function GuardarCondiciones($conn,$id,$condiciones){
		try {
			$JsonRec = new Services_JSON();
			$JsonRec=$JsonRec->decode(str_replace("\\","",$condiciones));
			$q = "DELETE FROM evaluacion_desincorporacion WHERE id_desincorporacion=$id";
			$r = $conn->Execute(utf8_encode($q));
			
			$this->auditoria($conn, $q);
			
			if(is_array($JsonRec->condiciones)){
				foreach($JsonRec->condiciones as $condicionesAux){

						$q = "INSERT INTO evaluacion_desincorporacion ";
						$q.= "(id_desincorporacion, id_componente, id_condicion) ";
						$q.= "VALUES ";
						$q.= "($id, $condicionesAux[0], NULLIF($condicionesAux[1],-1)); ";
						
						$conn->Execute(utf8_encode($q));
						
						$this->auditoria($conn, $q);
				}
	
			}
		}
		catch( ADODB_Exception $e ){
			if($e->getCode()==-1)
				return ERROR_CATCH_VFK;
			elseif($e->getCode()==-5)
				return ERROR_CATCH_VUK;
			else
				return ERROR_CATCH_GENERICO;
		}
	}
	
	function total_registro_busqueda($conn,$Tipo, $Valor, $TipoE, $orden="A.id")
	{
		$zona = $_SESSION['SesionZona'];
		$TipoE = empty($TipoE) ? 0 : $TipoE;
			if(empty($Valor)){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A WHERE A.id_zona = $zona ";
			}
			elseif($Tipo==0){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A ";
			$q.= "WHERE A.id_zona = $zona AND A.id::text ILIKE '%$Valor%'::text ";
			}
			elseif($Tipo==1){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A ";
			$q.= "WHERE A.id_zona = $zona AND A.numero::text ILIKE '%$Valor%'::text  ";
			}
			elseif($Tipo==2){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A ";
			$q.= "INNER JOIN personas AS B ON A.id_persona = B.id ";
			$q.= "WHERE A.id_zona = $zona AND B.cedula::text ILIKE '%$Valor%'::text  ";
			}
			elseif($Tipo==3){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A ";
			$q.= "INNER JOIN personas AS B ON A.id_persona = B.id ";
			$q.= "WHERE A.id_zona = $zona AND B.nombre::text ILIKE '%$Valor%'::text  ";
			}
			elseif($Tipo==4){
			$q = "SELECT count(*) AS total FROM desincorporaciones AS A ";
			$q.= "INNER JOIN vehiculos AS C ON B.id_vehiculo = C.id ";
			$q.= "WHERE A.id_zona = $zona AND C.placa::text ILIKE '%$Valor%'::text ";
			}

		$r = $conn->Execute(utf8_encode($q));
		$total = $r->fields['total'];
		return $total;
	}	

	function auditoria($conn, $query) {
		$id_usuario = $_SESSION['id'];
		$q = "INSERT INTO auditoria(id_usuario, query) VALUES($id_usuario,$$" . $query . "$$);";
		//die($q);
		$conn->Execute(utf8_encode($q));

		return true;
	}		
	
}
?>
